﻿#include "buss_order.h"
#include "ui_buss_order.h"
#include "buss_main.h"
#include <QSqlQuery>
#include <QSqlDatabase>
#include <QMessageBox>
#include <QVBoxLayout>
#include <QLabel>
#include <QSqlError>
#include <QDateEdit>
#include <QMap>
#include <QVariant>
#include <QtDebug>

Buss_order::Buss_order(int bus_id,QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Buss_order),
    bus_id(bus_id)
{
    ui->setupUi(this);
    setWindowTitle("订单管理");

    // 设置窗口大小
    resize(1200, 800);
    setMinimumSize(1000, 600);

    // 动态添加总营收标签
    if (!totalIncomeLabel) {
        totalIncomeLabel = new QLabel("总营收：0.00 元", this);
        totalIncomeLabel->setStyleSheet("font-size:16px;font-weight:bold;color:#333;margin:8px 0 8px 16px;");
        totalIncomeLabel->move(20, 10);
        totalIncomeLabel->show();
    }

    // 只加载已完成订单，前两个部分只显示暂无
    loadOrders("", QDate(), QDate(), true);

    // 回车键触发搜索
    connect(ui->lineEdit, &QLineEdit::returnPressed, this, &Buss_order::on_pushButton_serch_clicked);
}
void Buss_order::loadOrders(const QString &searchText, const QDate &startDate, const QDate &endDate, bool finishedOnly)
{
    QLayout *layout = ui->scrollAreaWidgetContents->layout();
    if (!layout) {
        layout = new QVBoxLayout(ui->scrollAreaWidgetContents);
        layout->setAlignment(Qt::AlignTop);
        ui->scrollAreaWidgetContents->setLayout(layout);
    }
    while (QLayoutItem *child = layout->takeAt(0)) {
        if (child->widget()) child->widget()->deleteLater();
        delete child;
    }
    // 辅助函数：安全字符串
    auto safeStr = [](const QVariant &v) { return v.isNull() ? QString("无") : v.toString(); };
    // 1. 可接单订单
    QLabel *label1 = new QLabel("可接单订单");
    label1->setStyleSheet("font-size:18px;font-weight:bold;margin:10px 0 5px 0;");
    layout->addWidget(label1);
    // 查询可接单订单 cs_id=4
    QString sql1 = R"(
SELECT o.order_id, c.com_name, o.quantity, u.user_name, o.address, p.phone AS user_phone, o.time_start
FROM order_c o
JOIN commodity c ON o.com_id = c.com_id
JOIN user u ON o.user_id = u.user_id
JOIN phone p ON u.phone_id = p.phone_id
WHERE o.business_id = :bus_id AND o.cs_id = 4
ORDER BY o.order_id DESC)";
    QSqlQuery query1;
    query1.prepare(sql1);
    query1.bindValue(":bus_id", bus_id);
    query1.exec();
    bool hasAvailable = false;
    while (query1.next()) {
        hasAvailable = true;
        int orderId = query1.value(0).toInt();
        QString comName = safeStr(query1.value(1));
        int quantity = query1.value(2).toInt();
        QString userName = safeStr(query1.value(3));
        QString address = safeStr(query1.value(4));
        QString userPhone = safeStr(query1.value(5));
        QString timeStart = safeStr(query1.value(6));
        QWidget *orderWidget = new QWidget;
        QVBoxLayout *vLayout = new QVBoxLayout(orderWidget);
        vLayout->addWidget(new QLabel(QString("菜品：%1  数量：%2  用户：%3").arg(comName).arg(quantity).arg(userName)));
        vLayout->addWidget(new QLabel(QString("地址：%1").arg(address)));
        vLayout->addWidget(new QLabel(QString("用户电话：%1").arg(userPhone)));
        vLayout->addWidget(new QLabel(QString("下单时间：%1").arg(timeStart)));
        QPushButton *acceptBtn = new QPushButton("接单");
        vLayout->addWidget(acceptBtn);
        connect(acceptBtn, &QPushButton::clicked, this, [=]() { onAcceptOrderClicked(orderId, acceptBtn); });
        orderWidget->setLayout(vLayout);
        layout->addWidget(orderWidget);
    }
    if (!hasAvailable) {
        QLabel *empty1 = new QLabel("暂无可接单订单");
        empty1->setStyleSheet("color:#888;margin-bottom:10px;");
        layout->addWidget(empty1);
    }

    // 2. 正在进行的订单
    QLabel *label2 = new QLabel("正在进行的订单");
    label2->setStyleSheet("font-size:18px;font-weight:bold;margin:20px 0 5px 0;");
    layout->addWidget(label2);
    // 查询正在进行的订单 cs_id=5,6,7
    QString sql2 = R"(
SELECT c.com_name, o.quantity, u.user_name, o.address, p.phone AS user_phone, rp.phone AS rider_phone, o.time_start, o.cs_id
FROM order_c o
JOIN commodity c ON o.com_id = c.com_id
JOIN user u ON o.user_id = u.user_id
JOIN phone p ON u.phone_id = p.phone_id
LEFT JOIN rider r ON o.rider_id = r.rider_id
LEFT JOIN phone rp ON r.phone_id = rp.phone_id
WHERE o.business_id = :bus_id AND o.cs_id IN (5,6,7)
ORDER BY o.order_id DESC)";
    QSqlQuery query2;
    query2.prepare(sql2);
    query2.bindValue(":bus_id", bus_id);
    query2.exec();
    bool hasOngoing = false;
    while (query2.next()) {
        hasOngoing = true;
        QString comName = safeStr(query2.value(0));
        int quantity = query2.value(1).toInt();
        QString userName = safeStr(query2.value(2));
        QString address = safeStr(query2.value(3));
        QString userPhone = safeStr(query2.value(4));
        QString riderPhone = safeStr(query2.value(5));
        QString timeStart = safeStr(query2.value(6));
        int csId = query2.value(7).toInt();
        QString statusText;
        if (csId == 5) statusText = "商家已接单";
        else if (csId == 6) statusText = "派送中";
        else if (csId == 7) statusText = "已送达";
        QWidget *orderWidget = new QWidget;
        QVBoxLayout *vLayout = new QVBoxLayout(orderWidget);
        vLayout->addWidget(new QLabel(QString("菜品：%1  数量：%2  用户：%3").arg(comName).arg(quantity).arg(userName)));
        vLayout->addWidget(new QLabel(QString("地址：%1").arg(address)));
        vLayout->addWidget(new QLabel(QString("用户电话：%1  骑手电话：%2").arg(userPhone).arg(riderPhone)));
        vLayout->addWidget(new QLabel(QString("下单时间：%1").arg(timeStart)));
        QLabel *statusLabel = new QLabel(statusText);
        statusLabel->setStyleSheet("color:#1976D2;font-weight:bold;padding:0 12px;");
        vLayout->addWidget(statusLabel);
        orderWidget->setLayout(vLayout);
        layout->addWidget(orderWidget);
    }
    if (!hasOngoing) {
        QLabel *empty2 = new QLabel("暂无正在进行的订单");
        empty2->setStyleSheet("color:#888;margin-bottom:10px;");
        layout->addWidget(empty2);
    }
    // 3. 已完成的订单
    QLabel *label3 = new QLabel("已完成的订单");
    label3->setStyleSheet("font-size:18px;font-weight:bold;margin:20px 0 5px 0;");
    layout->addWidget(label3);
    // 查询已完成订单
    QString sql3;
    QSqlQuery query3;
    bool hasFinished = false;
    bool hasDateFilter = startDate.isValid() && endDate.isValid();
    if (!searchText.isEmpty() && hasDateFilter) {
        sql3 = R"(
SELECT c.com_name, o.quantity, u.user_name, o.address, p.phone AS user_phone, rp.phone AS rider_phone, o.time_start, o.time_end
FROM order_c o
JOIN commodity c ON o.com_id = c.com_id
JOIN user u ON o.user_id = u.user_id
JOIN phone p ON u.phone_id = p.phone_id
LEFT JOIN rider r ON o.rider_id = r.rider_id
LEFT JOIN phone rp ON r.phone_id = rp.phone_id
WHERE o.business_id = :bus_id AND o.cs_id = 8
  AND (c.com_name LIKE :kw OR u.user_name LIKE :kw OR p.phone LIKE :kw)
  AND (o.time_end >= :startDate AND o.time_end <= :endDate)
ORDER BY o.order_id DESC)";
        query3.prepare(sql3);
        query3.bindValue(":bus_id", bus_id);
        query3.bindValue(":kw", "%" + searchText + "%");
        query3.bindValue(":startDate", startDate.toString("yyyy-MM-dd"));
        query3.bindValue(":endDate", endDate.toString("yyyy-MM-dd"));
    } else if (!searchText.isEmpty()) {
        sql3 = R"(
SELECT c.com_name, o.quantity, u.user_name, o.address, p.phone AS user_phone, rp.phone AS rider_phone, o.time_start, o.time_end
FROM order_c o
JOIN commodity c ON o.com_id = c.com_id
JOIN user u ON o.user_id = u.user_id
JOIN phone p ON u.phone_id = p.phone_id
LEFT JOIN rider r ON o.rider_id = r.rider_id
LEFT JOIN phone rp ON r.phone_id = rp.phone_id
WHERE o.business_id = :bus_id AND o.cs_id = 8
  AND (c.com_name LIKE :kw OR u.user_name LIKE :kw OR p.phone LIKE :kw)
ORDER BY o.order_id DESC)";
        query3.prepare(sql3);
        query3.bindValue(":bus_id", bus_id);
        query3.bindValue(":kw", "%" + searchText + "%");
    } else if (hasDateFilter) {
        sql3 = R"(
SELECT c.com_name, o.quantity, u.user_name, o.address, p.phone AS user_phone, rp.phone AS rider_phone, o.time_start, o.time_end
FROM order_c o
JOIN commodity c ON o.com_id = c.com_id
JOIN user u ON o.user_id = u.user_id
JOIN phone p ON u.phone_id = p.phone_id
LEFT JOIN rider r ON o.rider_id = r.rider_id
LEFT JOIN phone rp ON r.phone_id = rp.phone_id
WHERE o.business_id = :bus_id AND o.cs_id = 8
  AND (o.time_end >= :startDate AND o.time_end <= :endDate)
ORDER BY o.order_id DESC)";
        query3.prepare(sql3);
        query3.bindValue(":bus_id", bus_id);
        query3.bindValue(":startDate", startDate.toString("yyyy-MM-dd"));
        query3.bindValue(":endDate", endDate.toString("yyyy-MM-dd"));
    } else {
        sql3 = R"(
SELECT c.com_name, o.quantity, u.user_name, o.address, p.phone AS user_phone, rp.phone AS rider_phone, o.time_start, o.time_end
FROM order_c o
JOIN commodity c ON o.com_id = c.com_id
JOIN user u ON o.user_id = u.user_id
JOIN phone p ON u.phone_id = p.phone_id
LEFT JOIN rider r ON o.rider_id = r.rider_id
LEFT JOIN phone rp ON r.phone_id = rp.phone_id
WHERE o.business_id = :bus_id AND o.cs_id =8
ORDER BY o.order_id DESC)";
        query3.prepare(sql3);
        query3.bindValue(":bus_id", bus_id);
    }
    query3.exec();
    while (query3.next()) {
        hasFinished = true;
        QString comName = safeStr(query3.value(0));
        int quantity = query3.value(1).toInt();
        QString userName = safeStr(query3.value(2));
        QString address = safeStr(query3.value(3));
        QString userPhone = safeStr(query3.value(4));
        QString riderPhone = safeStr(query3.value(5));
        QString timeStart = safeStr(query3.value(6));
        QString timeEnd = safeStr(query3.value(7));
        QWidget *orderWidget = new QWidget;
        QVBoxLayout *vLayout = new QVBoxLayout(orderWidget);
        vLayout->addWidget(new QLabel(QString("菜品：%1  数量：%2  用户：%3").arg(comName).arg(quantity).arg(userName)));
        vLayout->addWidget(new QLabel(QString("地址：%1").arg(address)));
        vLayout->addWidget(new QLabel(QString("用户电话：%1  骑手电话：%2").arg(userPhone).arg(riderPhone)));
        vLayout->addWidget(new QLabel(QString("下单时间：%1  送达时间：%2").arg(timeStart).arg(timeEnd)));
        QLabel *finishedLabel = new QLabel("已完成");
        finishedLabel->setStyleSheet("color:#43A047;font-weight:bold;padding:0 12px;");
        vLayout->addWidget(finishedLabel);
        orderWidget->setLayout(vLayout);
        layout->addWidget(orderWidget);
    }
    if (!hasFinished) {
        QLabel *empty3 = new QLabel("暂无已完成的订单");
        empty3->setStyleSheet("color:#888;margin-bottom:10px;");
        layout->addWidget(empty3);
    }

    // 统计总营收
    double totalIncome = 0.0;
    {
        QString incomeSql = R"(
SELECT SUM(o.quantity * c.price)
FROM order_c o
JOIN commodity c ON o.com_id = c.com_id
WHERE o.business_id = :bus_id AND o.cs_id = 8
  AND date(o.time_end) >= :startDate AND date(o.time_end) <= :endDate
)";
        QSqlQuery incomeQuery;
        incomeQuery.prepare(incomeSql);
        incomeQuery.bindValue(":bus_id", bus_id);
        incomeQuery.bindValue(":startDate", startDate.isValid() ? startDate.toString("yyyy-MM-dd") : "0000-01-01");
        incomeQuery.bindValue(":endDate", endDate.isValid() ? endDate.toString("yyyy-MM-dd") : "9999-12-31");
        if (incomeQuery.exec() && incomeQuery.next()) {
            totalIncome = incomeQuery.value(0).toDouble();
        }
    }
    if (totalIncomeLabel) {
        totalIncomeLabel->setText(QString("总营收：%1 元").arg(totalIncome, 0, 'f', 2));
    }
}
Buss_order::~Buss_order()
{
    delete ui;
}
//跳转菜单主界面
void Buss_order::on_pushButton_return_clicked()
{
    Buss_main *b=new Buss_main;
    b->setBusiness1_id(bus_id);
    b->show();
    this->hide();
    return;
}
void Buss_order::on_pushButton_timefilter_clicked()
{
    QDate start = ui->dateEdit_start->date();
    QDate end = ui->dateEdit_end->date();
    QString searchText = ui->lineEdit->text();
    loadOrders(searchText, start, end, true); // 只查已完成订单
}
void Buss_order::on_pushButton_serch_clicked()
{
    QString searchText = ui->lineEdit->text();
    QDate start = ui->dateEdit_start->date();
    QDate end = ui->dateEdit_end->date();
    loadOrders(searchText, start, end, true); // 只查已完成订单
}
void Buss_order::onAcceptOrderClicked(int orderId, QPushButton *btn)
{
    QSqlQuery query;
    query.prepare("UPDATE order_c SET cs_id = 5 WHERE order_id = :order_id");
    query.bindValue(":order_id", orderId);
    if (query.exec()) {
        btn->setText("已接单");
        btn->setEnabled(false);
        QMessageBox::information(this, "成功", "接单成功，等待骑手抢单！");
    } else {
        QMessageBox::warning(this, "错误", "接单失败：" + query.lastError().text());
    }
}
